package com.rocky.pubimport.service.strategy;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rocky.pubimport.common.PubExcelTemplate;
import com.rocky.pubimport.entity.Order;
import com.rocky.pubimport.entity.PubImportData;
import com.rocky.pubimport.mapper.OrderMapper;
import com.rocky.pubimport.service.IPubImportRecordProcessService;
import com.rocky.pubimport.service.impl.PubImportRecordProcessServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 订单数据导入处理
 * @author rocky
 * @date 2022/5/7 9:45
 */
@Service
public class OrderImportServiceStrategy extends PubImportRecordProcessServiceImpl<Order> implements IPubImportRecordProcessService<Order> {

    @Resource
    private OrderMapper orderMapper;

    @Override
    protected String getModelCode() {
        return "ORDER";
    }

    @Override
    protected PubExcelTemplate getExcelTemplate() {
        PubExcelTemplate template = new PubExcelTemplate();
        template.setTemplateName("订单模板");
        template.getTitleRow().add("订单号");
        template.getTitleRow().add("金额");
        return template;
    }

    @Override
    protected void checkParams(Order data) {
       int count = orderMapper.selectCount(new QueryWrapper<Order>()
               .eq("`id`", data.getId()));
       if (count > 0) {
           throw new RuntimeException("导入的订单数据存在重复");
       }
    }

    @Override
    protected Order readData(PubImportData data) {
        if (StringUtils.isBlank(data.getValue1())) {
            throw new RuntimeException("订单编号不能为空");
        }
        if (data.getValue2() == null) {
            throw new RuntimeException("订单金额不能为空");
        }
        Order order = new Order();
        order.setOrderNo(data.getValue1());
        order.setAmount(new BigDecimal(data.getValue2()));
        return order;
    }

    @Override
    protected void saveData(Order data) {
        orderMapper.insert(data);
    }

    @Override
    protected void writeExpand(PubImportData importData, Order businessData) {
        // 反写订单ID
        importData.setValue3(businessData.getId().toString());
    }
}
